package com.hps.spring.cloud.alibaba.util;

import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

/**
 * @author heps
 * @since 2020/11/5 9:00
 */
public class SecurityUtil {

  private SecurityUtil() {}

  public static String getCurrentUsername() {
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal instanceof UserDetails) {
      return ((UserDetails)principal).getUsername();
    }
    return principal.toString();
  }

  @SuppressWarnings("unchecked")
  public static Map<String, Object> getCurrentUserInfo() {
    OAuth2Authentication auth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
    Map<String, Object> detail = (Map<String, Object>) auth2Authentication.getUserAuthentication().getDetails();
    if (Objects.nonNull(detail)) {
      return (Map<String, Object>) detail.get("principal");
    }
    return Collections.emptyMap();
  }
}
